package com.huixiong.nio.channel.socket;

import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.file.StandardOpenOption;

/**
 * <描述>
 *
 * @author timothy.yang cloudwise
 * @since 2022-05-08 21:52
 */
public class SocketChannelDemo {
    @SneakyThrows
    public static void main(String[] args) {
        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress("http://jenkov.com", 80));

//        SocketChannel channel2 = SocketChannel.open(new InetSocketAddress("www.baidu.com", 80));

        // 检验
        channel.isOpen();//是否开启
        channel.isConnected();
        channel.isConnectionPending();// 是否正在连接
        channel.finishConnect();

        channel.configureBlocking(false);

        ByteBuffer buf = ByteBuffer.allocate(16);
        channel.read(buf);
        channel.close();
        System.out.println("read over");

        // 设置参数
        channel.setOption(StandardSocketOptions.SO_KEEPALIVE,Boolean.TRUE);
    }
}
